import cv2
import numpy as np
import matplotlib.pyplot as plt
# 读取字帖图像
img = cv2.imread('hanzi1.jpg')
# 转换为灰度图
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
#全局阈值化处理
# 应用全局阈值处理
_, binary = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)
# 创建一个4x4 的方形内核
kernel = np.ones((4,4),np.uint8)
# 执行腐蚀操作
eroded = cv2.erode(binary, kernel, iterations=2)
# 执行膨胀操作
dilated = cv2.dilate(eroded, kernel, iterations=4)
# 应用中值滤波
median = cv2.medianBlur(dilated, 5)
# 执行闭运算操作
closed = cv2.morphologyEx(median, cv2.MORPH_CLOSE, kernel, iterations=12)
# 应用Canny边缘检测
edges = cv2.Canny(closed, 100, 200)
contours, hierarchy = cv2.findContours(edges, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
for i, contour in enumerate(contours):
    x, y, w, h = cv2.boundingRect(contour)
    if w > 10 and h > 10:  # 过滤掉太小的轮廓
        char_img = img[y:y+h, x:x+w]
        cv2.imwrite(f'chars/char_{i+1}.jpg', char_img)
plt.figure(figsize=(16, 4))
plt.subplot(1,7,1)
plt.imshow(gray, cmap='gray')
plt.title('Gray Image')
plt.axis('off')
plt.subplot(1, 7, 2)
plt.imshow(binary, cmap='gray')
plt.title('Binary Image')
plt.axis('off')
plt.subplot(1, 7, 3)
plt.imshow(eroded, cmap='gray')
plt.title('Eroded Image')
plt.axis('off')
plt.subplot(1, 7, 4)
plt.imshow(median, cmap='gray')
plt.title('Median Filtered Image')
plt.axis('off')
plt.subplot(1, 7, 5)
plt.imshow(closed, cmap='gray')
plt.title('Closed Image')
plt.axis('off')
plt.subplot(1, 7, 6)
plt.imshow(edges, cmap='gray')
plt.title('Canny Edges')
plt.axis('off')
plt.subplot(1, 7, 7)
plt.imshow(img, cmap='gray')
for contour in contours:
    x, y, w, h = cv2.boundingRect(contour)
    cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2)
plt.imshow(img, cmap='gray')
plt.title('Canny ziti')
plt.axis('off')
plt.tight_layout()
plt.show()
